package com.yuke.cloud.service.uac.controller.frontend;

import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.dto.LoginAuthDto;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.annotation.LogAnnotation;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.uac.exceptions.UacBizException;
import com.yuke.cloud.service.uac.dto.AccRoleCheckCodeDto;
import com.yuke.cloud.service.uac.dto.AccRoleCheckNameDto;
import com.yuke.cloud.service.uac.dto.RoleMainQueryDto;
import com.yuke.cloud.service.uac.entity.AccRole;
import com.yuke.cloud.service.uac.entity.AccUserRole;
import com.yuke.cloud.service.uac.service.AccRoleService;
import com.yuke.cloud.service.uac.service.AccUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* Created by wg on 2018/11/05.
*/
@Api(value = "WEB - AccRoleController", tags = "处理AccRole相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/acc/role")
public class AccRoleController extends BaseController {
    @Resource
    private AccRoleService accRoleService;
    @Resource
    private AccUserRoleService accUserRoleService;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "accRole", value = "该数据记录的POJO") @RequestBody AccRole accRole) {
//        accRoleService.save(accRole);
//        return WrapMapper.ok();

        return UpdateOrAddRole(accRole);
    }

    @LogAnnotation
    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
//        accRoleService.deleteById(id);
//        return WrapMapper.ok();

        int result = accRoleService.deleteRoleById(id);
        return super.handleResult(result);
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "accRole", value = "需要修改的内容") @RequestBody AccRole accRole) {
//        accRoleService.update(accRole);
//        return WrapMapper.ok();
        return UpdateOrAddRole(accRole);
    }

    private Wrapper UpdateOrAddRole(AccRole accRole) {
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        accRoleService.saveRole(accRole, loginAuthDto);
        return WrapMapper.ok(accRole);
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<AccRole> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        AccRole accRole = accRoleService.findById(id);
        return WrapMapper.ok(accRole);
    }

    @PostMapping("/getAllList")
    @ApiOperation(httpMethod = "POST", value = "获取所有记录")
    public Wrapper<List<AccRole>> list() {
        List<AccRole> list = accRoleService.findAll();
        return WrapMapper.ok(list);
    }

    /**
     * 分页查询角色信息.
     *
     * @param role the role
     *
     * @return the wrapper
     */
    @PostMapping(value = "/getRoleList")
    @ApiOperation(httpMethod = "POST", value = "查询角色列表")
    public Wrapper<PageInfo<AccRole>> queryUacRoleListWithPage(@ApiParam(name = "role", value = "角色信息") @RequestBody RoleMainQueryDto role) {
        PageInfo pageInfo = accRoleService.queryRoleListWithPage(role);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 批量删除角色.
     *
     * @param deleteIdList the delete id list
     *
     * @return the wrapper
     */
    @LogAnnotation
    @PostMapping(value = "/batchDeleteByIdList")
    @ApiOperation(httpMethod = "POST", value = "批量删除角色")
    public Wrapper batchDeleteByIdList(@ApiParam(name = "deleteIdList", value = "角色Id") @RequestBody List<Long> deleteIdList) {
        logger.info("批量删除角色 idList={}", deleteIdList);
        accRoleService.batchDeleteByIdList(deleteIdList);
        return WrapMapper.ok();
    }

    /**
     * 修改角色状态.
     *
     * @param accRole the modify status dto
     *
     * @return the wrapper
     */
    @LogAnnotation
    @PutMapping(value = "/modifyRoleStatusById")
    @ApiOperation(httpMethod = "PUT", value = "根据角色Id修改角色状态")
    public Wrapper modifyUacRoleStatusById(@ApiParam(name = "modifyRoleStatusDto", value = "修改角色状态数据") @RequestBody AccRole accRole) {
        logger.info("根据角色Id修改角色状态 accRole={}", accRole);
        Long roleId = accRole.getRoleId();
        if (roleId == null) {
            throw new UacBizException(ErrorCodeEnum.UAC10012001);
        }

        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Long userId = loginAuthDto.getUserId();

        AccUserRole ur = accUserRoleService.getByUserIdAndRoleId(userId, roleId);

        if (ur != null && !accRole.getIsEnable()) {
            throw new UacBizException(ErrorCodeEnum.UAC10012002);
        }

        accRole.setUpdateId(userId);
        accRole.setUpdateTime(new Date());

        int result = accRoleService.update(accRole);
        return super.handleResult(result);
    }

    /**
     * 验证角色编码是否存在.
     *
     * @param checkRoleCodeDto the check role code dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/checkCode")
    @ApiOperation(httpMethod = "POST", value = "验证角色编码是否存在")
    public Wrapper<Boolean> checkUacRoleCode(@ApiParam(name = "roleCode", value = "角色编码") @RequestBody AccRoleCheckCodeDto checkRoleCodeDto) {

        logger.info("校验角色编码唯一性 checkRoleCodeDto={}", checkRoleCodeDto);

        Long id = checkRoleCodeDto.getRoleId();
        String roleCode = checkRoleCodeDto.getRoleCode();

        Example example = new Example(AccRole.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andNotEqualTo("roleId", id);
        }
        criteria.andEqualTo("roleCode", roleCode);

        int result = accRoleService.selectCountByExample(example);
        return WrapMapper.ok(result < 1);
    }

    /**
     * 检测角色名称是否已存在
     *
     * @param accRoleCheckNameDto the acc role check code dto
     *
     * @return the wrapper
     */
    @PostMapping(value = "/checkName")
    @ApiOperation(httpMethod = "POST", value = "检测角色名称是否已存在")
    public Wrapper<Boolean> checkRoleName(@ApiParam(name = "accRoleCheckNameDto", value = "id与name")
                                            @RequestBody AccRoleCheckNameDto accRoleCheckNameDto) {

        Long id = accRoleCheckNameDto.getRoleId();
        String roleName = accRoleCheckNameDto.getRoleName();

        Example example = new Example(AccRole.class);
        Example.Criteria criteria = example.createCriteria();

        if (id != null) {
            criteria.andNotEqualTo("roleId", id);
        }
        criteria.andEqualTo("roleName", roleName);

        int result = accRoleService.selectCountByExample(example);
        return WrapMapper.ok(result < 1);
    }
}
